package com.smarthospital.service.impl;

import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.common.util.SHDateUtil;
import com.smarthospital.dao.daoService.MedicalCardMapperService;
import com.smarthospital.entity.pojo.MedicalCard;
import com.smarthospital.entity.pojo.User;
import com.smarthospital.service.MedicalCardService;
import com.smarthospital.web.inteceptor.LoginInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * create by sym  2021/8/1 14:32.
 */
@Service
@Slf4j
public class MedicalCardServiceImpl implements MedicalCardService {

    @Autowired
    private MedicalCardMapperService medicalCardMapperService;

    @Override
    public MedicalCard queryMine(String  hospitalCode) {
        User user = LoginInterceptor.getUser();
        return medicalCardMapperService.queryByUserIdAndHos(user.getId(),hospitalCode);
    }

    @Override
    public void register(MedicalCard medicalCard) {
        //todo   短信验证码 暂时放行
        medicalCardMapperService.insertSelective(medicalCard);
    }

    @Override
    public void update(MedicalCard medicalCard) {
        medicalCardMapperService.update(medicalCard);
    }

    /**
     * 返回值  0-未注册  1-已经注册
     *
     * @param medicalCard
     * @return
     */
    @Override
    public Integer check(MedicalCard medicalCard) {
        if (medicalCard == null) {
            throw new CommonException(CodeMsg.ERROR_PARAM);
        }

        MedicalCard medicalCardDb;
        if (StringUtils.isEmpty(medicalCard.getHospitalCode())) {
            List<MedicalCard> medicalCards = medicalCardMapperService.queryByUserId(LoginInterceptor.getUser().getId());
            medicalCardDb = medicalCards.stream().max((c1,c2)-> SHDateUtil.compareDateTime(c1.getCreateTime(),c2.getCreateTime())).orElse(null);
        }else {
            medicalCardDb = medicalCardMapperService.queryByUserIdAndHos(LoginInterceptor.getUser().getId(), medicalCard.getHospitalCode());
        }

        return medicalCardDb == null?0:1;
    }
}
